/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package web;

import ejb.CategoryBeanLocal;
import entities.Category;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ejb.EJB;
import javax.el.ExpressionFactory;
import javax.el.MethodExpression;
import javax.faces.application.Application;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIParameter;
import javax.faces.component.behavior.ClientBehaviorContext.Parameter;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import org.primefaces.component.menuitem.MenuItem;
import org.primefaces.component.panelmenu.PanelMenu;
import org.primefaces.component.submenu.Submenu;

/**
 *
 * @author Alejandro
 */
@ManagedBean
@SessionScoped
public class MenuBean implements Serializable {

    private PanelMenu panelMenu;
    @EJB
    private CategoryBeanLocal categoryBean;

    public MenuBean() {
    }

    public PanelMenu getPanelMenu() {
        //TODO comentar if para no regenerar en cada carga
        boolean update= Constants.getNeedUpdateMenu();
        if (panelMenu == null || update) {
            generateMenu();
            Constants.setNeedUpdateMenu(Boolean.FALSE);
        }
        return panelMenu;
    }

    public void setPanelMenu(PanelMenu panelMenu) {
        this.panelMenu = panelMenu;
    }

    public void generateMenu() {

        ExpressionFactory ef = ExpressionFactory.newInstance();
        //ef.createValueExpression(FacesContext.getCurrentInstance().getELContext(), "#{}", String.class, .class);
        //ExpressionFactory.createMethodExpression(javax.el.ELContext, java.lang.String, java.lang.Class, java.lang.Class[]).

        panelMenu = new PanelMenu();
        List<Category> parents = categoryBean.findChildrenForParent();
        List<Category> children = categoryBean.findAllChildren();
        //Se obtiene  padres ordenados
        Collections.sort(parents);


        Map<Integer, List<Category>> mapChildren = new HashMap<Integer, List<Category>>();
        //Se indexan los hijos en un mapa idPadre, lista de hijos.
        for (Category child : children) {
            if (mapChildren.containsKey(child.getParentCategory().getIdCategory())) {
                mapChildren.get(child.getParentCategory().getIdCategory()).add(child);
            } else {
                List<Category> l = new ArrayList<Category>();
                l.add(child);
                mapChildren.put(child.getParentCategory().getIdCategory(), l);
            }
        }

        for (Category par : parents) {
            

            List<Category> lChildren = mapChildren.get(par.getIdCategory());
            if(lChildren!=null){
            Submenu submenu = new Submenu();
            submenu.setLabel(par.getName());
            Collections.sort(lChildren);
            for (Category child : lChildren) {
                MenuItem item = new MenuItem();
                item.setValue(child.getName());
                item.setAjax(false);
                //item.handleAttribute("holaa2", "textoiotem");
               UIParameter para = new UIParameter();
               para.setName("asd");
               para.setValue("asdasd");
               
               item.getChildren().add(para);
                
                Application app = FacesContext.getCurrentInstance().getApplication();
                MethodExpression methodExpression = app.getExpressionFactory().createMethodExpression(
                        FacesContext.getCurrentInstance().getELContext(),
                        "#{menuBean.goTo("+child.getIdCategory()+")}",
                        null,
                        new Class[]{ActionEvent.class});
                //TODO FIXME cambiar la navegacion por URL
                // item.setUrl(child.getIdCategory().toString());
                item.setActionExpression(methodExpression);
//                Parameter p = new Parameter("Nombreparam", 2);
               
                
                //item.getChildren().add(new Parame);
                submenu.getChildren().add(item);
            }
            panelMenu.getChildren().add(submenu);
        }

//        Submenu submenu1 = new Submenu();
//        submenu1.setLabel("Categoria");
//        MenuItem item1 = new MenuItem();
//        item1.setValue("Item1");
//        MenuItem item2 = new MenuItem();
//        item2.setValue("Item2");
//        submenu1.getChildren().add(item1);
//        submenu1.getChildren().add(item2);
//        panelMenu.getChildren().add(submenu1);
        }
    }
    
    public String goTo(Integer idCat){
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(Constants.NEXT_VIEW,Constants.CATEGORY+Constants.SEPARATOR+idCat);
        return "UPDATE";
    }
}
